<template>
  <div class="tabs-container">
    <div class="tabs-header">
      <span
        v-for="(tab, index) in tabs"
        :key="index"
        :class="['tab', activeTab === index ? 'active' : '']"
        @click="switchTab(index)"
      >
        {{ tab.name }}
        <span v-if="tab.count !== undefined" class="tab-count">{{ tab.count }}</span>
      </span>
    </div>
    <slot :activeTabIndex="activeTab"></slot>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";

interface Tab {
  name: string;
  [key: string]: any; // 允许其他自定义属性
}

// 定义组件属性
const props = defineProps<{
  tabs: Tab[];
  defaultActive?: number;
}>();

// 定义事件
const emit = defineEmits<{
  (e: "tab-change", index: number): void;
}>();

// 当前激活的选项卡
const activeTab = ref(props.defaultActive || 0);

// 切换选项卡
const switchTab = (index: number) => {
  activeTab.value = index;
  emit("tab-change", index);
};

// 监听默认值变化
watch(
  () => props.defaultActive,
  (newVal) => {
    if (newVal !== undefined) {
      activeTab.value = newVal;
    }
  }
);
</script>

<style scoped>
.tabs-container {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.tabs-header {
  display: flex;
  margin-top: 12px;
  flex-wrap: nowrap;
  overflow-x: auto;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
  padding-bottom: 5px; /* 为滚动条留出空间 */
}

/* 隐藏滚动条 */
.tabs-header::-webkit-scrollbar {
  display: none;
}

.tab {
  margin-right: 15px;
  padding: 4px 0;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  position: relative;
  white-space: nowrap;
  display: flex;
  align-items: center;
}

.tab-count {
  margin-left: 4px;
  font-size: 12px;
  background-color: #f0f0f0;
  color: #999;
  border-radius: 10px;
  padding: 0 6px;
  min-width: 16px;
  height: 16px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.tab.active {
  color: #263961;
  font-weight: 500;
}

.tab.active .tab-count {
  background-color: rgba(38, 57, 97, 0.1);
  color: #263961;
}

.tab.active::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #263961;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .tabs-header {
    padding-bottom: 8px;
  }
  
  .tab {
    font-size: 13px;
    margin-right: 12px;
    padding: 3px 0;
  }
  
  .tab-count {
    font-size: 11px;
    padding: 0 5px;
    min-width: 14px;
    height: 14px;
  }
}

@media (max-width: 480px) {
  .tabs-header {
    margin-top: 8px;
  }
  
  .tab {
    font-size: 12px;
    margin-right: 10px;
  }
  
  .tab.active::after {
    height: 1.5px;
  }
}
</style>
